import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.parser.Tag;
import org.jsoup.select.Elements;

public class HtmlParseUtil {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String path = "/Users/zhaoyang/eclipse-workspace/HTML/src/bdqn.html";
		Map<Tag, Integer> tags = searchTag(path);
		for (Tag key : tags.keySet()) {
			System.out.println("<" + key + "> =>> " + tags.get(key) + "次");
		}

	}

	public static Map<Tag, Integer> searchTag(String path) {
		Map<Tag, Integer> tags = new HashMap<>();
		String url = readHTML(path);
		Document document = Jsoup.parse(url);
		Elements elements = document.getAllElements();
		for (Element el : elements) {
			// System.out.println(el.tag());
			// 标签已存在，则数量+1，否则新建标签=1
			int count = tags.containsKey(el.tag()) ? tags.get(el.tag()) : 0;
			tags.put(el.tag(), count + 1);
		}
		return tags;
	}

	public static Map<Tag, Integer> searchTagFromURL(String url) throws MalformedURLException, IOException {
		Map<Tag, Integer> tags = new HashMap<>();
		Document document = Jsoup.parse(new URL(url), 5000);
		Elements elements = document.getAllElements();
		for (Element el : elements) {
			// System.out.println(el.tag());
			// 标签已存在，则数量+1，否则新建标签=1
			int count = tags.containsKey(el.tag()) ? tags.get(el.tag()) : 0;
			tags.put(el.tag(), count + 1);
		}
		return tags;
	}

	public static String readHTML(String path) {
		try {
			String pathname = path;
			// File对象
			File filename = new File(pathname);
			// 文件字节输入流对象
			FileInputStream fileInputStream = new FileInputStream(filename);
			// 字节转字符输入流对象 InputStreamReader：字节流到字符流的桥梁
			InputStreamReader reader = new InputStreamReader(fileInputStream, "utf-8");
			// BufferedReader(字符缓冲输入流)，提供通用的缓冲方式文本读取
			BufferedReader br = new BufferedReader(reader);
			// 多线程StringBuffer 单线程StringBuilder
			StringBuffer txt = new StringBuffer();
			String line = "";
			while ((line = br.readLine()) != null) {

				txt.append(line + ";");
			}
			// 方法一：流的关闭：先打开的后关闭，后打开的先关闭
			// 方法二：可以只调用外层流的close方法关闭其装饰的内层流
			br.close();
			return txt.toString();
		} catch (Exception e) {
			// e.printStackTrace();
			return null;
		}
	}

}
